package link.idns.g01.jdbcbridge.utils;

import java.sql.SQLException;
import java.util.concurrent.ConcurrentHashMap;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;

import link.idns.g01.jdbcbridge.domain.JdbcDataSource;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class PoolManager {

    // 所有数据源的连接池存在map里
    static ConcurrentHashMap<String, DruidDataSource> map = new ConcurrentHashMap<>();

    public static DruidDataSource getJdbcConnectionPool(JdbcDataSource jdbcDataSource) {
        if (map.containsKey(jdbcDataSource.getUrl())) {
            return map.get(jdbcDataSource.getUrl());
        } else {

            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setName(jdbcDataSource.getUrl());
            druidDataSource.setUrl(jdbcDataSource.getUrl());
            druidDataSource.setUsername(jdbcDataSource.getUsername());
            druidDataSource.setPassword(jdbcDataSource.getPassword());
            druidDataSource.setDriverClassName(jdbcDataSource.getDriver());
            druidDataSource.setConnectionErrorRetryAttempts(3); // 失败后重连次数
            druidDataSource.setBreakAfterAcquireFailure(true);

            // try {
            // druidDataSource.setPassword(DESUtils.decrypt(jdbcDataSource.getPassword()));
            // } catch (Exception e) {
            // throw new RuntimeException(e);
            // }

            map.put(jdbcDataSource.getUrl(), druidDataSource);
            // log.info("create druid datasource：{}", ds.getName());
            return druidDataSource;
        }
    }

    // 删除数据库连接池
    public static void removeJdbcConnectionPool(String id) {
        if (map.containsKey(id)) {
            DruidDataSource old = map.get(id);
            map.remove(id);
            old.close();
            log.info("remove druid datasource: {}", old.getName());
        }
    }

    public static DruidPooledConnection getPooledConnection(JdbcDataSource jdbcDataSource) throws SQLException {
        DruidDataSource pool = PoolManager.getJdbcConnectionPool(jdbcDataSource);
        DruidPooledConnection connection = pool.getConnection();
        // log.info("获取连接成功");
        return connection;
    }
}
